package com.terren.spider.util.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class FileUtil{
	/**
	 * 清空目录
	 * @param filepath
	 */
	public static void cleanDirectory(String filepath) {
		try {
			File file = new File(filepath);
			if (file.exists()) {
				FileUtils.cleanDirectory(file);
			}
		} catch (IOException e) {
			LogUtil.logger.error("cleanDirectory error",e);
		}
	}
	/**
	 * 清空目录
	 * @param filepath
	 */
	public static void delDirectory(String filepath) {
		try {
			File file = new File(filepath);
			if (file.exists()) {
				FileUtils.deleteDirectory(file);
			}
		} catch (IOException e) {
			LogUtil.logger.error("cleanDirectory error",e);
		}
	}
	/**
	 * 创建文件夹
	 * @param path
	 */
	public static void mkdirs(String path) {
		File file = new File(path);
		if(!file.exists()){
			file.mkdirs();
		}
	}
	/** 读取文件夹中的所有文件，返回字符串列表
     * @param filePath
     * @return
     */
    public static List<String> readAllFile(String filePath) {
    	StringBuilder str = new StringBuilder();
    	List<String> jsonList=new ArrayList<>();
		try {
			String encoding = "utf-8";
			File file = new File(filePath);
			String[] fileArray=file.list();
			for (int i = 0; i < fileArray.length; i++) {
				if (fileArray[i].length()!=0) { // 判断文件是否存在
					InputStreamReader read = new InputStreamReader(new FileInputStream(filePath+"//"+fileArray[i]), encoding);// 考虑到编码格式
					BufferedReader bufferedReader = new BufferedReader(read);
					String lineTxt = null;
					while ((lineTxt = bufferedReader.readLine()) != null){
						str.append(lineTxt);
					}
					read.close();
				} else {
					System.out.println("找不到指定的文件");
				}
				jsonList.add(str.toString());
			}
			
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return jsonList;

	}
    
    /** 读取文件中的字符返回字符串
     * @param filePath
     * @return
     */
    public static String readFile(String filePath) {
    	StringBuilder str = new StringBuilder();
		try {
			String encoding = "utf-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) { // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null){
					str.append(lineTxt+"\r\n");
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return str.toString();

	}

}
